package cn.easybuy.servlet.users;

import cn.easybuy.entity.User;
import cn.easybuy.service.UserService;
import cn.easybuy.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/userAddServlet")
public class UserAddServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        try {
            String username = request.getParameter("loginname");
            String pwd = request.getParameter("Pwd");
            String identityCode = request.getParameter("identityCode");
            String sex = request.getParameter("sex");
            String email = request.getParameter("Email");
            String phone = request.getParameter("Phone");
            User u = new User(username, pwd);
            u.setPassword(pwd);
            u.setSex(Integer.parseInt(sex));
            u.setEmail(email);
            u.setUserName(username);
            u.setMobile(phone);
            u.setIdentityCode(identityCode);
            u.setType(0);
            User user = userService.selectUserInfo(u);
            if (user != null) {
                request.setAttribute("msg", "手机号或邮箱已绑定用户");
            } else {
                request.setAttribute("msg", "注册成功");
                userService.AddNews(u);
            }
            request.getRequestDispatcher("pre/register.jsp").forward(request, response);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
